package cc.mrbird.assets.service.impl;

import cc.mrbird.assets.dao.AssetManaMapper;
import cc.mrbird.assets.dao.AssetUnitMapper;
import cc.mrbird.assets.domain.AssetMana;
import cc.mrbird.assets.domain.AssetUnit;
import cc.mrbird.assets.service.AssetManaService;
import cc.mrbird.assets.service.AssetUnitService;
import cc.mrbird.common.domain.QueryRequest;
import cc.mrbird.common.exception.FileImportException;
import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.system.domain.User;
import cc.mrbird.unit.dao.UnitInfoMapper;
import cc.mrbird.unit.dao.UserUnitMapper;
import cc.mrbird.unit.domain.UnitInfo;
import cc.mrbird.unit.domain.UserUnit;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service("assetManaService")
public class AssetManaServiceImpl extends BaseService<AssetMana> implements AssetManaService {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AssetManaMapper assetManaMapper;
    @Autowired
    private AssetUnitMapper assetUnitMapper;
    @Autowired
    private UserUnitMapper userUnitMapper;
    @Autowired
    private UnitInfoMapper unitInfoMapper;
    @Autowired
    private AssetUnitService assetUnitService;
    @Override
    public List<AssetMana> findAllList(AssetMana assetMana, QueryRequest request) {
        try {
            return this.assetManaMapper.findAllList(assetMana);
        } catch (Exception e) {
            log.error("error", e);
            return new ArrayList<>();
        }
    }
    @Override
    public void add(AssetMana assetMana ,User user) {
        UserUnit unitIdByUser = userUnitMapper.findUnitIdByUser(user.getUserId());
        UnitInfo unitInfo = unitInfoMapper.findByUnitId(unitIdByUser.getUnit_id());
        String unit_name = unitInfo.getUnit_name();
        assetMana.setDeployment_location(unit_name+assetMana.getDeployment_location());
        assetMana.setUnit_id(unitInfo.getUnit_id());
        assetManaMapper.save(assetMana);
        Integer assetMana_id = assetMana.getAssetMana_id();
        setAssetUnits(assetMana,unitIdByUser);
    }
    private void setAssetUnits(AssetMana assetMana, UserUnit userUnit) {
        AssetUnit assetUnit = new AssetUnit();
        assetUnit.setAsset_id(assetMana.getAssetMana_id());
        assetUnit.setUnit_id(userUnit.getUnit_id());
        this.assetUnitMapper.insert(assetUnit);
    }
    @Override
    public AssetMana findById(Long id) {
        try {
            return this.assetManaMapper.findById(id);
        } catch (Exception e) {
            log.error("error", e);
            return new AssetMana();
        }
    }

    @Override
    @Transactional
    public void delete(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        this.batchDelete(list, "assetMana_id", AssetMana.class);
        this.assetUnitService.deleteAssetUnitByAssetId(ids);
    }

    @Override
    public void update(AssetMana assetMana) {
        this.assetManaMapper.update(assetMana);
    }

    @Override
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        List<AssetMana> assetManaList = new ArrayList<AssetMana>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new FileImportException("上传文件格式不正确");
        }
        boolean isExcel2003 = false;
        if (fileName.matches("^.+\\.(?i)(xls)$")) {
            isExcel2003 = true;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (!isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        AssetMana assetMana;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            assetMana = new AssetMana();

            String asset_type = row.getCell(0).getStringCellValue();
            if(asset_type == null || asset_type.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,资产类型未填写)");
            }
            String deployment_location =row.getCell(1).getStringCellValue();
            if(deployment_location==null || deployment_location.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,部署位置未填写)");
            }
            String camera_ID = row.getCell(2).getStringCellValue();
            if(camera_ID==null ||camera_ID.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,摄像头ID未填写)");
            }
            String information_plan = row.getCell(3).getStringCellValue();
            if(information_plan==null ||information_plan.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,位置信息平面图未填写)");
            }
            String safety_officer = row.getCell(4).getStringCellValue();
            if(safety_officer==null ||safety_officer.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,安全负责人未填写)");
            }
            String security_inspector = row.getCell(5).getStringCellValue();
            if(security_inspector==null ||security_inspector.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,安全巡查人未填写)");
            }
            row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
            String equipment_status = row.getCell(6).getStringCellValue();
            if(equipment_status==null ||equipment_status.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,设备状态未填写)");
            }
            String patrol_point = row.getCell(7).getStringCellValue();
            if(patrol_point==null ||patrol_point.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,是否是巡查点未填写)");
            }
            String manufacturers = row.getCell(8).getStringCellValue();
            if(manufacturers==null ||manufacturers.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,生产厂商未填写)");
            }
            String discard_time = row.getCell(9).getStringCellValue();
            if(discard_time==null ||discard_time.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,报废时间未填写)");
            }

            String construction_unit = row.getCell(10).getStringCellValue();
            if(construction_unit==null ||construction_unit.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,施工单位未填写)");
            }
            assetMana.setAsset_type(asset_type);
            assetMana.setDeployment_location(deployment_location);
            assetMana.setCamera_ID(camera_ID);
            assetMana.setInformation_plan(information_plan);
            assetMana.setSafety_officer(safety_officer);
            assetMana.setSecurity_inspector(security_inspector);
            assetMana.setEquipment_status(Integer.parseInt(equipment_status));
            assetMana.setPatrol_point(patrol_point);
            assetMana.setManufacturers(manufacturers);
            Date parse = sdf.parse(discard_time);
            assetMana.setDiscard_time(parse);
            assetMana.setConstruction_unit(construction_unit);

            assetManaList.add(assetMana);
        }
        for (AssetMana assetMana1 : assetManaList) {
                this.save(assetMana1);
        }
        return notNull;
    }
}
